var pd = require('pd'),
    zlib = require('zlib'),
    http = require('http'),
    ee = require('eventemitter-light');

module.exports = {
    request: function request(resource) {
        var encoding = '';
        
        if (!resource.headers) {
            resource.headers = {};
        } else if (resource.headers['Accept-Encoding']) {
            encoding = resource.headers['Accept-Encoding'];
        }
    
        // Make sure we request gzip encoding, if necessary
        if (!/(^|\s|,)gzip(\s|,|$)/.test(encoding)) {
            resource.headers['Accept-Encoding'] = 'gzip' +
                (encoding ? ',' : '') + encoding;
        }
    
        var get = http.get(resource, (function get(response) {
            if (response.statusCode === 200) {
                var isCompressed = response.headers['content-encoding'] === 'gzip',
                    responseBody = '',
                    gzip = isCompressed ? new zlib.createGunzip() : null;
                    
                // Make sure we handle the response as normal content
                // if the response is not gzipped (might still not be
                // right, but then the caller or server is just trolls)
                if (isCompressed) {
                    response.pipe(gzip);
                    response = gzip;
                }
                
                // Decompress the response body as it comes in
                response.on('data', function chunk(chunk) {
                    responseBody += chunk;
                });
                
                // Join the response data
                response.on('end', (function end() {
                    this.emit('complete', responseBody, resource);
                }).bind(this));
            } else {
                this.emit('error', response, resource);
            }
        }).bind(this));
        
        get.on('error', (function error(error) {
            this.emit('error', error, resource);
        }).bind(this));
    },
    constructor: function constructor() {
        pd.bindAll(this);
        pd.extend(this, ee, { constructor: constructor });
        ee.constructor.call(this);
        
        return this;
    }
};